//
//  SEGActivityDetailBaseViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/1.
//  Copyright © 2017年 陈区. All rights reserved.
//

// ViewController
#import "SEGActivityDetailBaseViewController.h"
#import "SEGActivityCommentDetailViewController.h"
#import "SEGActivityRootViewController.h"

#if __has_include(<SEGStandard/SEGShareViewController.h>)
#import <SEGStandard/SEGShareViewController.h>
#else
#import "SEGShareViewController.h"
#endif

// View
#import "SEGActivityDeletedView.h"
#import "SEGNaviTitleNomalView.h"
#import <SEGPlatform/SEGActivityLotteryBubbleButton.h>

#if __has_include(<SEGStandard/SEGAdvertisementView.h>)
#import <SEGStandard/SEGAdvertisementView.h>
#else
#import "SEGAdvertisementView.h"
#endif

// Model
#import <SEGPlatform/SEGAdDisplayManager.h>
// Third
#import "GDTUnifiedBannerView.h"


@interface SEGActivityDetailBaseViewController () <UITableViewDelegate, UITableViewDataSource, SEGNaviTitleNomalViewDelegate, SEGActivityRuleDelegate ,SEGActivityDetailToolBarDelegate ,SEGCommentInputViewDelegate ,SEGActivityDetailCommentCellDelegate ,SEGActivityNoCommentDelegate ,SEGActivityDeletedViewDelegate ,GDTUnifiedBannerViewDelegate>

@property (nonatomic, strong) UIButton* backBtn;
/// 所有活动按钮
@property (nonatomic, strong) UIButton* allButton;
@property (nonatomic, strong) UIButton* sharedButton;
@property (nonatomic, strong) SEGNaviTitleNomalView* naviTitle;
/// 广告轮播视图
@property (nonatomic, strong)SEGAdvertisementView *adView;
@property (nonatomic, strong) SEGActivityLotteryBubbleButton *lotteryButton;
/// 是否开启留言板
@property (nonatomic, assign) BOOL isReview;
/// 活动是否被删除
@property (nonatomic, assign) BOOL hasBeenDeleted;
/// cell高度缓存
@property (nonatomic, strong) NSMutableDictionary *cellHightDict;
/// 腾讯广告
@property (nonatomic, strong) GDTUnifiedBannerView *bannerView;
/// 腾讯广告-判断用户是否点击关闭
@property (nonatomic, assign) BOOL bannerViewIsClosed;
@property (nonatomic, assign) BOOL bannerViewLoadSuccess;

@end

@implementation SEGActivityDetailBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化数据
    self.displayTypeArray = @[@(SEGActivityDetailCellDispalyType_Rule), @(SEGActivityDetailCellDispalyType_TencentAD), @(SEGActivityDetailCellDispalyType_Comment)];
    self.detailModel = [[SEGActivityDetailModel alloc] init];
    self.detailViewModel.actId = self.actId;
    
    // SetupUI
    self.toolBarView = [[SEGActivityDetailToolBarView alloc] init];
    self.toolBarView.delegate = self;
    self.toolBarView.hidden = YES;
    self.toolBarView.isFromActivity = YES; ///< 处理toolbar会抢commentInputView焦点的问题
    [self.view addSubview:self.toolBarView];
    [self.toolBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(LYSafeAreaBottom());
        make.height.mas_equalTo(activityToolBarNormalHeight + LYSafeAreaBottom());
    }];
    
    self.view.backgroundColor = kColor_W;
    self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.bottom.equalTo(self.toolBarView.mas_top);
    }];
    [self seg_setupNavigationView];
    
    // 拉取数据
    WeakSelf;
    [self.tableView addWindmillWithHeaderRefreshBlock:^{
        [weakSelf headerRereshing];
    } footerRefreshBlock:^{
        [weakSelf footerRereshing];
    }];
    [self.tableView beginHeaderRefreshing];
    [self loadTencentAd];
    
    // 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(seg_shareSucceed) name:NOTIFICATION_SHARESUCCEED object:nil];
    //收到活动抽奖推送
    [[NSNotificationCenter defaultCenter] addObserverForName:SEGActivityLotteryNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf seg_checkActivityLotteryBubble];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self seg_checkActivityLotteryBubble];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.commentInputView.hidden = NO;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.commentInputView.hidden = YES;
}

/// 判断是否显示活动抽奖气泡
- (void)seg_checkActivityLotteryBubble {
    [[SEGUhomeMediator sharedInstance] seg_checkActivityLotteryBubble:@{@"vc" : self}];
}

- (void)dealloc {
    [self.commentInputView removeFromSuperview];
    self.commentInputView = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_SHARESUCCEED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SEGActivityLotteryNotification object:nil];
    
    if (self.bannerView) {
        [self.bannerView removeFromSuperview];
        self.bannerView = nil;
    }
}

/// 显示没有认证的时候显示提示框
- (void)showNothAlterView {
    SEGNewAlertView *alertView = [[SEGNewAlertView alloc] init];
    [alertView showWithAlertTitle:nil text:@"亲~该功能需物业管理处认证后方可使用" buttonTitlesArray:@[@"取消", @"申请认证"] actionBlock:^(NSInteger btnIndex) {
        if (btnIndex == 1) {
            [self goToAuthViewController];
        }
    }];
}

- (void)goToAuthViewController {
    UIViewController *VC = [[SEGUhomeMediator sharedInstance] seg_initSubmitUserAtuhViewController:nil];
    VC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 刷新控件
//添加刷新控件 步骤2
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.hasBeenDeleted) {
        [self.naviTitle setHidden:NO];
        return;
    }
    if (scrollView.contentOffset.y > LYScreenHeight() * 0.25) {
        [self.naviTitle setHidden:NO];
        return;
    }
    [self.naviTitle setHidden:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    /* [bugfix 34658]
     当线下活动填写资料的时候，如果姓名一栏显示不全的时候，点击弹出键盘时，tableview会自动滚一点点，显示完姓名一栏
     和scrollViewDidScroll中去掉键盘的事件冲突了
     */
    [self.view endEditing:YES];
}

//头部刷新逻辑
- (void)headerRereshing {
    [self requsetActivityDetail];
    [self requestCommentList:YES];
    [self requestOtherInfoWhenRefresh];
}

// 底部刷新逻辑
- (void)footerRereshing {
    [self requestCommentList:NO];
}

// 请求活动详情
- (void)requsetActivityDetail {
    __weak typeof (self) weakSelf = self;
    [self.detailViewModel.requestActicityDeatilSignal subscribeNext:^(id  _Nullable x) {
        // 处理数据
        weakSelf.detailModel = (SEGActivityDetailModel *)x;
        weakSelf.naviTitle.contentLabel.text = weakSelf.detailModel.actName;
        SEGActivityType type = [weakSelf.detailModel.actType integerValue];
        weakSelf.isReview = [weakSelf.detailModel.isReview isEqualToString:@"2"] ? YES : NO;
        BOOL isLikeed = [weakSelf.detailModel.isLikeed isEqualToString:@"1"] ? YES : NO;
        [weakSelf.toolBarView setUpViewWithType:type status:[weakSelf.detailModel.actStatus integerValue] isReview:weakSelf.isReview isLikeed:isLikeed likeCount:weakSelf.detailModel.praiseCount triggerEvent:weakSelf.detailModel.triggerEvent];
        weakSelf.toolBarView.hidden = NO;
        // 展示活动头部图片
        NSMutableArray<SEGAdvertismentModel*> *adSource = [NSMutableArray array];
        [weakSelf.detailModel.actPic enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SEGAdvertismentModel *model = [[SEGAdvertismentModel alloc] init];
            model.pic = obj;
            [adSource addObject:model];
        }];
        SEGAdvertisementViewModel *data = [[SEGAdvertisementViewModel alloc]init];
        data.adSource = adSource;
        data.widgetWidth = LYScreenWidth();
        SEGAdvertisementViewLayout *layout = [[SEGAdvertisementViewLayout alloc] initWithData:data type:SEGEnumAdvertismentType_ACT];
        [weakSelf.adView setWithLayout:layout];

        [weakSelf.tableView reloadData];
        [weakSelf requestOtherInfoAfterDetail];
    } error:^(NSError * _Nullable error) {
        if (error.code == -3) { //活动被删除 显示删除界面
            weakSelf.hasBeenDeleted = YES;
            [weakSelf.naviTitle setHidden:NO];
            SEGActivityDeletedView *deletedView = [[SEGActivityDeletedView alloc] initWithFrame:CGRectMake(0, kNavigationBarAndStatusBarHeight, LYScreenWidth(), LYScreenHeight() - kNavigationBarAndStatusBarHeight)];
            deletedView.delegate = weakSelf;
            [weakSelf.view addSubview:deletedView];
            return;
        }
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

- (void)requestCommentList:(BOOL)isRefresh {
    //请求评论列表
    __weak typeof (self) weakSelf = self;
    [[self.detailViewModel requestCommentList:isRefresh] subscribeNext:^(id  _Nullable x) {
        [weakSelf.tableView stopAnimatingWindmill];
        [weakSelf.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        [weakSelf.tableView stopAnimatingWindmill];
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

#pragma mark - 根据不同类型活动进行界面设置 子类根据需要重写
/// 下拉刷新时需要请求其他的数据
- (void)requestOtherInfoWhenRefresh {
    
}

/// 请求详情后请求其他数据
- (void)requestOtherInfoAfterDetail {
    
}

/// 返回section中的行数
- (NSInteger)setRowsInSection:(NSInteger)section {
    return 0;
}

/// 返回cell
- (UITableViewCell *)setCellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"noUseCellId"];
}

/// 设置cell高度
- (CGFloat)setHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 0;
}

/// 设置点击cell后的操作
- (void)afterSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.displayTypeArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    SEGActivityDetailCellDispalyType dispalyType = [self.displayTypeArray[section] integerValue];
    if (dispalyType == SEGActivityDetailCellDispalyType_Rule) {
        return 1;
    }
    if (dispalyType == SEGActivityDetailCellDispalyType_TencentAD) {
        return 1;
    }
    if (dispalyType == SEGActivityDetailCellDispalyType_Comment) {
        if ([self.detailModel.isReview isEqualToString:@"1"]) {//不开启留言板
            return 0;
        }
        if (self.detailViewModel.commentsArray.count > 0) {
            return self.detailViewModel.commentsArray.count + 1;
        }else {
            return 2;
        }
    }
    return [self setRowsInSection:section];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGActivityDetailCellDispalyType dispalyType = [self.displayTypeArray[indexPath.section] integerValue];
    if (dispalyType == SEGActivityDetailCellDispalyType_Rule) {
        //规则说明
        SEGActivityDetailRuleCell *cell = [tableView dequeueReusableCellWithIdentifier:kActivityDetailRuleCellIdentifier forIndexPath:indexPath];
        cell.delegate = self;
        [cell setUpCellWithDescription:self.detailModel.rulesDesc isCollectVC:[self.detailModel.actType isEqualToString:@"1"]];
        return cell;
    }
    if (dispalyType ==  SEGActivityDetailCellDispalyType_TencentAD) {//腾讯广告
        // 腾讯广告
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
        }
        
        UIView *subView = (UIView *)[cell.contentView viewWithTag:1000];
        if ([subView superview]) {
            [subView removeFromSuperview];
        }
        if (!self.bannerViewIsClosed) {
            self.bannerView.tag = 1000;
            [cell.contentView addSubview:self.bannerView];
            self.bannerView.width = LYScreenWidth();
            cell.accessibilityIdentifier = @"nativeTemp_even_ad";
        }
        return cell;
    }
    if (dispalyType == SEGActivityDetailCellDispalyType_Comment) {//邻居说
        if (indexPath.row == 0) {//标题
            SEGActivityDetailTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:kActivityDetailTitleCellIdentifier forIndexPath:indexPath];
            return cell;
        }else {
            if (self.detailViewModel.commentsArray.count == 0) {//没有评论 显示缺省界面
                SEGActivityDetailNoCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:kActivityDetailNoCommentCellIdentifier forIndexPath:indexPath];
                cell.delegate = self;
                return cell;
            }else {
                SEGActivityDetailCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:kActivityDetailCommentCellIdentifier forIndexPath:indexPath];
                cell.delegate = self;
                [cell setUpCellWithCommentModel:self.detailViewModel.commentsArray[indexPath.row - 1] indexPath:indexPath];
                return cell;
            }
        }
    }
    
    //活动主体
    return [self setCellForRowAtIndexPath:indexPath];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *key = [NSString stringWithFormat:@"%ld-%ld", (long)indexPath.section, (long)indexPath.row];
    [self.cellHightDict setObject:@(cell.frame.size.height) forKey:key];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath*)indexPath {
    NSString *key = [NSString stringWithFormat:@"%ld-%ld", (long)indexPath.section, (long)indexPath.row];
    CGFloat height = [[self.cellHightDict objectForKey:key] floatValue];
    if (height == 0) height = 100.f;
    return height;
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    SEGActivityDetailCellDispalyType dispalyType = [self.displayTypeArray[indexPath.section] integerValue];
    if(dispalyType == SEGActivityDetailCellDispalyType_TencentAD) { //腾讯广告
        if (self.bannerViewIsClosed || self.bannerViewLoadSuccess == false){
            return 0.0;
        }
        //腾讯广告
        if (self.bannerView) return self.bannerView.size.height;
        return 60.0;
    }
    
    return UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    SEGActivityDetailCellDispalyType dispalyType = [self.displayTypeArray[section] integerValue];
    if (dispalyType == SEGActivityDetailCellDispalyType_Rule) {
        return 0.01;
    }
    if (dispalyType == SEGActivityDetailCellDispalyType_TencentAD) {
        if (self.bannerViewIsClosed || self.bannerViewLoadSuccess == false) {
            return CGFLOAT_MIN;
        }
    }
    if (dispalyType == SEGActivityDetailCellDispalyType_Comment && [self.detailModel.isReview isEqualToString:@"1"]) { //邻居说 不开启留言板
        return 0.01;
    }
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 10.0)];
    header.backgroundColor = kColor_bg;
    return header;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SEGActivityDetailCellDispalyType dispalyType = [self.displayTypeArray[indexPath.section] integerValue];
    if (dispalyType == SEGActivityDetailCellDispalyType_Comment) {//邻居说
        if (self.detailViewModel.commentsArray.count == 0) {
            return;
        }
        if(indexPath.row != 0 && self.detailViewModel.commentsArray.count > indexPath.row - 1) {
            SEGActivityCommentDetailViewController *vc = [[SEGActivityCommentDetailViewController alloc] initWithQuizId:self.detailViewModel.commentsArray[indexPath.row - 1].quizId actId:self.actId actName:self.detailModel.actName];
            [self.navigationController pushViewController:vc animated:YES];
        }
    } else {
        [self afterSelectRowAtIndexPath:indexPath];
    }
}

#pragma mark - SEGNaviTitleNomalViewDelegate代理
- (void)naviTitleNomalViewBackButtonPressed {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - SEGActivityDetailToolBarDelegate
- (void)activityShouldShowInputView:(BOOL)showInputView {
    if (showInputView) {
        [self seg_requestCheckActivityUnaudit];
    }
}

//对活动点赞
- (void)praiseButtonAction {
    @weakify(self);
    [self.detailViewModel.requestPraiseActivitySignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        NSString *likeCount = (NSString *)x;
        SEGActivityType type = [self.detailModel.actType integerValue];
        [self.toolBarView setUpViewWithType:type status:[self.detailModel.actStatus integerValue] isReview:self.isReview isLikeed:YES likeCount:likeCount triggerEvent:self.detailModel.triggerEvent];
        self.toolBarView.hidden = NO;
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

#pragma mark - <SEGCommentInputViewDelegate>

//发送评论
- (void)sendButtonActionWithContent:(NSString *)content {
    [SVProgressHUD show];
     __weak typeof (self) weakSelf = self;
    [[self.detailViewModel.submitCommnetCommand execute:content] subscribeNext:^(id  _Nullable x) {
        [SVProgressHUD dismiss];
        //发送成功后在收起和清空输入框
        [weakSelf.view endEditing:YES];
        [weakSelf.commentInputView hiddenCommentInputView];
        //刷新评论列表
        [weakSelf requestCommentList:YES];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
        if (error.code == 1001) {
            [weakSelf.view endEditing:YES];
            [weakSelf.commentInputView hiddenCommentInputView];
            //刷新评论列表
            [weakSelf requestCommentList:YES];
        }
    }];
}

- (void)afterTouchCommentInputView {
    
}

#pragma mark - SEGActivityRuleDelegate
- (void)changeRuleViewHeight {
    [self.tableView reloadData];
}

#pragma mark - SEGActivityDetailCommentCellDelegate
//对邻居说评论评论
- (void)cellCommentButtonActionWithIndexPath:(NSIndexPath *)indexPath {
    //直接进入评论详情页
    SEGActivityCommentDetailViewController *vc = [[SEGActivityCommentDetailViewController alloc] initWithQuizId:self.detailViewModel.commentsArray[indexPath.row - 1].quizId actId:self.actId actName:self.detailModel.actName];
    [self.navigationController pushViewController:vc animated:YES];
}

//对邻居说评论点赞
- (void)cellPraiseButtonActionWithIndexPath:(NSIndexPath *)indexPath {
    SEGActivityDetailCommentModel *model = self.detailViewModel.commentsArray[indexPath.row - 1];
    [[self.detailViewModel.praiseCommentCommand execute:model] subscribeNext:^(id  _Nullable x) {
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

- (void)cellImageTapWithImageUrlArray:(NSArray *)arr SelectedImageView:(UIImageView*)image SelectedIndex:(NSInteger)index {
    [SEGPhotoBrower segBrowPhotoWithDataArray:arr
                            SelectedImageView:image
                                SelectedIndex:index
                                     FromView:self.navigationController.view];
}

#pragma mark - SEGActivityNoCommentDelegate
- (void)noCommentButtonClick {
    if ([self.detailModel.actStatus integerValue] == SEGActivityStatus_NotBegin) {
        [SEGAlertView showTmepMessageWithMessage:@"亲！活动还未开始，请稍后再试哦！"];
    } else if ([self.detailModel.actStatus integerValue] == SEGActivityStatus_Over) {
        [SEGAlertView showTmepMessageWithMessage:@"亲，活动已结束，下次早点来吧！"];
    } else {
        [self seg_requestCheckActivityUnaudit];
    }
}

#pragma mark - 私有方法
- (void)seg_requestCheckActivityUnaudit {
    __weak typeof (self) weakSelf = self;
    [self.detailViewModel.checkActivityExamineSignal subscribeNext:^(id  _Nullable x) {
        [weakSelf.commentInputView setPlaceholderText:KInputToolBarDefalutDesc];
        [weakSelf.commentInputView showCommentInputView];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

- (void)seg_setupNavigationView {
    [self.view addSubview:self.backBtn];
    [self.view addSubview:self.allButton];
    [self.view addSubview:self.sharedButton];
    [self.view addSubview:self.naviTitle];
    [self.naviTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(kNavigationBarAndStatusBarHeight);
    }];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        if (LYIsiPhoneX()) { //适配iPhoneX 下移15
            make.top.equalTo(self.view).offset(45);
        }else {
            make.top.equalTo(self.view).offset(30);
        }
    }];
    [self.allButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.sharedButton.mas_left).offset(-15);
        make.top.equalTo(self.backBtn);
    }];
    [self.sharedButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-15);
        make.top.equalTo(self.backBtn);
    }];
}

- (void)seg_backBtnClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)seg_allBtnClick {
    // 如果当前导航堆栈不存在列表则创建，否则直接返回
    BOOL flag = NO;
    UIViewController *rootVC = nil;
    for (UIViewController *subVC in self.navigationController.viewControllers) {
        if ([subVC isKindOfClass:[SEGActivityRootViewController class]]) {
            rootVC = subVC;
            flag = YES;
            break;
        }
    }
    if (flag) {
        [self.navigationController popToViewController:rootVC animated:YES];
    } else {
        SEGActivityRootViewController *vc = [[SEGActivityRootViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)seg_sharedButtonClick {
    NSString *imageUrl = [NSString stringWithFormat:@"%@%@",kClientImageRootURL,self.detailModel.sharePic];
    NSString *shareUrl = [NSString stringWithFormat:@"%@/h5/activity-h5-version2/?#/uhomeShare?isSharePage=1&actId=%@&scheme=%@",kClientRootURL , self.actId, kOpenAppScheme];//拼接应用的scheme
    NSDictionary *params = @{
                             @"shareVCType":@(SEGShareVCType_Activity),
                             @"objID":self.actId,
                             @"shareImageUrlString":imageUrl,
                             @"sharetitle":self.detailModel.shareTitle,
                             @"sharecontent":self.detailModel.shareDigest,
                             @"inviteurl":shareUrl
                             };
    UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initShareViewController:params actionType:^(NSInteger actionType) {
        
    } channel:^(NSString *channel) {
        
    }];
    vc.objName = self.detailModel.actName;
    [self presentViewController:vc animated:NO completion:nil];
}

- (void)seg_shareSucceed {
    UIViewController *vc = self.navigationController.visibleViewController;
    if ([vc isEqual:self]) {//当前显示的控制器
        //提交分享记录
        [self.detailViewModel.submitShareRecordSignal subscribeNext:^(id  _Nullable x) {
        }];
    }
}

#pragma mark - SEGActivityDeletedViewDelegate
- (void)goToAllActivityVC {
    SEGActivityRootViewController *vc = [[SEGActivityRootViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 腾讯广告
- (void)loadTencentAd {
    if(![[SEGAdDisplayManager shared] getAdWhetherShow:SEGAD_ActivityDetailType]) return;
    
    if (self.bannerView.superview) {
        [self.bannerView removeFromSuperview];
        self.bannerView = nil;
    }

    CGRect rect = {CGPointZero, CGSizeMake(375, 60)};
    GDTUnifiedBannerView *bannerView = [[GDTUnifiedBannerView alloc] initWithFrame:rect placementId:kGDTPosIdSharedActivityRules viewController:self];
    bannerView.accessibilityIdentifier = @"banner_ad";
    bannerView.autoSwitchInterval = 30;
    bannerView.delegate = self;
    self.bannerView = bannerView;
    
    [self.view addSubview:self.bannerView];
    [self.bannerView loadAdAndShow];
}

#pragma mark - GDTUnifiedBannerViewDelegate
- (void)unifiedBannerViewDidLoad:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"请求广告条数据成功后调用,当接收服务器返回的广告数据成功后调用该函数%s",__FUNCTION__);
}
- (void)unifiedBannerViewFailedToLoad:(GDTUnifiedBannerView *)unifiedBannerView error:(NSError *)error{
    [self.bannerView removeFromSuperview];
    self.bannerView = nil;
    self.bannerViewLoadSuccess = false;
    if(![[[NSUserDefaults standardUserDefaults] valueForKey:kUserDefaultIsProduction] boolValue]){[SEGAlertView showTmepMessageWithMessage:error.localizedDescription];}
    NSLog(@"请求广告条数据失败后调用,当接收服务器返回的广告数据失败后调用该函数%s",__FUNCTION__);
}
- (void)unifiedBannerViewWillExpose:(GDTUnifiedBannerView *)unifiedBannerView{
    self.bannerViewLoadSuccess = true;
    [self.tableView reloadData];
    NSLog(@"banner2.0曝光回调%s height:%f",__FUNCTION__,unifiedBannerView.bounds.size.height);
}
- (void)unifiedBannerViewClicked:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"banner2.0点击回调%s",__FUNCTION__);
}
- (void)unifiedBannerViewWillPresentFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"banner2.0广告点击以后即将弹出全屏广告页%s",__FUNCTION__);
}
- (void)unifiedBannerViewDidPresentFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"banner2.0广告点击以后弹出全屏广告页完毕%s",__FUNCTION__);
}
- (void)unifiedBannerViewWillDismissFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"全屏广告页即将被关闭%s",__FUNCTION__);
}
- (void)unifiedBannerViewDidDismissFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"全屏广告页已经被关闭%s",__FUNCTION__);
}
- (void)unifiedBannerViewWillLeaveApplication:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"当点击应用下载或者广告调用系统程序打开%s",__FUNCTION__);
}
- (void)unifiedBannerViewWillClose:(GDTUnifiedBannerView *)unifiedBannerView{
    self.bannerViewIsClosed = YES;
    [self.tableView reloadData];
    self.bannerView = nil;
    NSLog(@"banner2.0被用户关闭时调用%s",__FUNCTION__);
}
#pragma mark - getter
- (SEGNaviTitleNomalView*)naviTitle {
    if (!_naviTitle) {
        _naviTitle = [[SEGNaviTitleNomalView alloc] initWithFrame:CGRectZero];
        _naviTitle.btnDelegate = self;
        _naviTitle.hidden = YES;
    }
    return _naviTitle;
}

- (UIButton*)backBtn {
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_header_back")] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(seg_backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

- (UIButton *)allButton {
    if (!_allButton) {
        _allButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_allButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_all")] forState:UIControlStateNormal];
        [_allButton addTarget:self action:@selector(seg_allBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _allButton;
}

- (UIButton*)sharedButton {
    if (!_sharedButton) {
        _sharedButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sharedButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_header_share")] forState:UIControlStateNormal];
        [_sharedButton addTarget:self action:@selector(seg_sharedButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sharedButton;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)- activityToolBarNormalHeight + 0.5 - LYSafeAreaBottom()) style:UITableViewStyleGrouped];//+0.5为了最后一根分割线和底部工具栏分割线重合
        _tableView.backgroundColor = kColor_bg;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = kColor_L2;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
        [_tableView registerClass:[SEGActivityDetailRuleCell class] forCellReuseIdentifier:kActivityDetailRuleCellIdentifier];
        [_tableView registerClass:[SEGActivityDetailTitleCell class] forCellReuseIdentifier:kActivityDetailTitleCellIdentifier];
        [_tableView registerClass:[SEGActivityDetailNoCommentCell class] forCellReuseIdentifier:kActivityDetailNoCommentCellIdentifier];
        [_tableView registerClass:[SEGActivityDetailCommentCell class] forCellReuseIdentifier:kActivityDetailCommentCellIdentifier];
        
        //适配iOS11
        if(@available(iOS 11.0, *)){
            //解决tableView不吸顶问题
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            //解决tableView间距不对问题
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
        }else{
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight = 100;
        _tableView.tableHeaderView = self.adView;
        _tableView.tableFooterView = [[UIView alloc] init];
    }
    return _tableView;
}

- (SEGAdvertisementView*)adView {
    if (!_adView) {
        _adView = [[SEGAdvertisementView alloc] initWithFrame:CGRectZero];
    }
    return _adView;
}

- (SEGCommentInputView *)commentInputView {
    if (!_commentInputView) {
        _commentInputView = [[SEGCommentInputView alloc] init];
        _commentInputView.currentViewController = self;//用于广告
        _commentInputView.delegate = self;
        _commentInputView.GDTPosId = KGDTPosIdActivityCommentListID;
        [self.view addSubview:_commentInputView];
    }
    return _commentInputView;
}

- (NSMutableDictionary *)cellHightDict {
    if (!_cellHightDict) _cellHightDict = [NSMutableDictionary new];
    return _cellHightDict;
}

- (SEGActivityDetailViewModel *)detailViewModel {
    if (!_detailViewModel) {
        _detailViewModel = [[SEGActivityDetailViewModel alloc] init];
    }
    return _detailViewModel;
}

@end
